package com.fsh.lingsp.common.user.service.handler;

import com.fsh.lingsp.common.user.service.WXMsgService;
import com.fsh.lingsp.common.user.service.adapter.TextBuilder;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 作者：fsh
 * 日期：2024/02/24
 * <p>
 * 描述：关注订阅处理程序
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    private WXMsgService wxMsgService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage,
                                    Map<String, Object> map,
                                    WxMpService wxMpService,
                                    WxSessionManager wxSessionManager) throws WxErrorException {
        String openId = wxMpXmlMessage.getFromUser();
        String eventKeyCode = wxMpXmlMessage.getEventKey();
        String event = wxMpXmlMessage.getEvent();
        logger.info("SubscribeHandler.handle()===>新用户扫码关注了" +
                ",openId={},eventKeyCode={},event={}",openId,eventKeyCode,event);

        WxMpXmlOutMessage wxMpXmlOutMessage=null;
        wxMpXmlOutMessage=wxMsgService.scan(wxMpXmlMessage,wxMpService);

        //如果不是null，直接返回
        if (wxMpXmlOutMessage != null){
            return wxMpXmlOutMessage;
        }

        // 如果是null，代表新用户关注。
        return TextBuilder.build("感谢关注",wxMpXmlMessage,wxMpService);
    }
}
